<template>
	<view class="flex flex-col h-screen">
		<NavBarVue title="登录" :leftIcon="false"></NavBarVue>
		<view class="flex flex-col justify-center items-center px-30">
			<view class="w-138 h-[138rpx] rounded-lg overflow-hidden mt-40">
				<ImageBoxVue src="/static/login/icon_logo.png" width="138rpx" height="138rpx"></ImageBoxVue>
			</view>
			<view class="bg-login mt-30">
				<uni-easyinput class="my-20" type="tel" :inputBorder="false" v-model="phone" placeholder="请输入电话">
					<template #left>
						<ImageBoxVue class="ml-20" src="/static/login/icon_phone.png" width="40rpx" height="40rpx">
						</ImageBoxVue>
					</template>
				</uni-easyinput>
				<uni-easyinput class="my-20" type="number" :inputBorder="false" v-model="code" placeholder="请输入验证码">
					<template #left>
						<ImageBoxVue class="ml-20" src="/static/login/icon_code.png" width="40rpx" height="40rpx">
						</ImageBoxVue>
					</template>
					<template #right>
						<view class="mini text-[#329EFF] p-10" @click="getCode">{{codeNum==0?'获取验证码': `${codeNum}s重试`	}}
						</view>
					</template>
				</uni-easyinput>
				<view class="flex justify-center items-center rounded-full bg-[#329EFF] text-white p-20 text-lg"
					@click="onLogin">登录</view>
			</view>
			<view class="">
				<AgreementVue v-model="isAgree"></AgreementVue>
			</view>
			<view class="box-other flex flex-col justify-center">
				<ImageBoxVue class="mt-40" src="/static/login/login_title.png" width="577rpx" height="26rpx">
				</ImageBoxVue>
				<view class="flex">
					<view class="flex-1 flex justify-center items-center">
						<view class="flex flex-col justify-center items-center" @click="handleLogin">
							<ImageBoxVue class="mt-40" src="/static/login/icon_wx.png" width="92rpx" height="92rpx">
							</ImageBoxVue>
							<text class="mt-20">微信</text>
						</view>
					</view>
					<view class="flex-1 flex flex-col justify-center items-center">
						<view class="flex flex-col justify-center items-center">
							<ImageBoxVue class="mt-40" src="/static/login/icon_apple.png" width="92rpx" height="92rpx">
							</ImageBoxVue>
							<text class="mt-20">苹果</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onBeforeUnmount
	} from 'vue';
	import indexApi from '@/apis/apiList/indexApi.js';
	import userApi from '@/apis/apiList/userApi';
	import AgreementVue from './components/Agreement.vue';
	import liveApi from "@/apis/apiList/liveApi.js"
	import TencentCloudChat from '@tencentcloud/chat';
	import {
		tim,
		initTIM,
		addMessageListener,
		removeMessageListener,
	} from "@/apis/IM.js"

	const codeNum = ref(0)
	const code = ref('')
	const phone = ref("")
	const isAgree = ref(false)
	const messageListener = ref(null)

	onBeforeUnmount(() => {
		// 移除消息监听
		if (messageListener.value) {
			removeMessageListener(messageListener.value);
		}

	})

	const membergetLiveTokens = () => {
		// 获取用户签名
		liveApi.membergetLiveTokens({
			id: `${uni.getStorageSync('user').id}`
		}).then(res => {
			// 初始化腾讯云IM
			initTencentIM(res.data.code);
		})
	}

	const initTencentIM = async (userSig) => {
		try {
			// 替换为你的腾讯云IM配置
			const options = {
				SDKAppID: 1400752704, // 你的应用SDKAppID
				userID: `${uni.getStorageSync('user').id}`, // 当前用户ID
				userSig: userSig // 当前用户签名
			};
			uni.setStorageSync('txOption', options)
			// 初始化TIM
			await initTIM(options);

			// 添加全局消息监听
			messageListener.value = (event, data) => {
				console.log('收到TIM事件:', event, data);

				// 根据事件类型处理不同消息
				switch (event) {
					case 'MESSAGE_RECEIVED':
						handleNewMessage(data);
						break;
					case 'MESSAGE_REVOKED':
						handleRevokedMessage(data);
						break;
					case 'CONVERSATION_UPDATED':
						handleConversationUpdate(data);
						break;
					case 'KICKED_OUT':
						handleKickedOut(data);
						break;

						// 其他事件处理...
				}
			};

			addMessageListener(messageListener.value);
			getApp().globalData.tim = tim
			console.log(tim);
			uni.reLaunch({
				url: "/pages/tabbar/test"
			})
		} catch (error) {
			uni.showToast({
				title: '初始化腾讯云IM失败'
			})
			console.error('初始化腾讯云IM失败:', error);
		}
	}

	const sendMsg = (fromAccount, payload) => {
		console.log(fromAccount, payload);
		const message = tim.createCustomMessage({
			to: fromAccount,
			conversationType: TencentCloudChat.TYPES.CONV_C2C,
			payload: payload,
		});
		tim.sendMessage(message);
	}

	// 处理新消息
	const handleNewMessage = (messages) => {
		// messages 是消息数组
		messages.forEach(message => {
			console.log('处理新消息:', message);
			const msg = message.payload
			if (msg.data == 'phone') {
				const {
					nickname,
					headimg
				} = JSON.parse(msg.extension)
				uni.redirectTo({
					url: `/pages/views/makePhone?type=receive&fromAccount=${msg.description}&info=${JSON.stringify({name:nickname,headimg:headimg})}`
				})
			}
			if (msg.data == 'unPhone') {
				uni.reLaunch({
					url: '/pages/tabbar/msg'
				})
			}
			if (msg.data == 'privateChat') privateChat(msg.description, '')
		});
	}
	const privateChat = (anchorId, id) => {
		uni.redirectTo({
			url: `/pages/msg/privateChat?anchorId=${anchorId}&id=${id}`
		})
	}
	// 处理撤回消息
	const handleRevokedMessage = (messages) => {
		messages.forEach(message => {
			console.log('消息被撤回:', message);
			// 处理消息撤回逻辑
		});
	}

	// 处理会话更新
	const handleConversationUpdate = (conversations) => {
		console.log('会话更新:', conversations);
		uni.showToast({
			icon: 'none',
			title: '会话更新'
		})
		// 处理会话更新逻辑
	}

	// 处理被踢下线
	const handleKickedOut = (data) => {
		console.log('被踢下线:', data);
		// uni.showModal({
		// 	title: '提示',
		// 	content: '您的账号在其他设备登录，已被踢下线',
		// 	showCancel: false,
		// 	success: () => {
		// 		// 跳转到登录页或其他处理
		// 	}
		// });
	}

	const handleLogin = () => {
		if (!isAgree.value) {
			uni.showToast({
				icon: "none",
				title: "请同意隐私协议和用户协议！"
			})
			return
		}
		uni.login({
			"provider": "weixin",
			"onlyAuthorize": true, // 微信登录仅请求授权认证
			success: function(event) {
				const {
					code
				} = event
				//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
				const opt = {
					code: event.code
				}
				indexApi.wxcodeLogin(opt).then(res => {
					if (res.data.ach == 1) {
						queryAnchorInfoByMemberId(res.data.id)
					}
					uni.setStorageSync('user', res.data)
					uni.setStorageSync('token', res.data.token)
					membergetLiveTokens()

				})
			}
		})

	}
	const getCode = () => {
		indexApi.getCode({
			phone: phone.value
		}).then(res => {
			uni.showToast({
				title: "发送成功"
			})
			codeNum.value = 60
			const time = setInterval(() => {
				codeNum.value--
				if (codeNum.value <= 0) clearInterval(time)
			}, 1000)
		})
	}
	const onLogin = () => {
		if (!phone.value) {
			uni.showToast({
				icon: "none",
				title: "请输入手机号！"
			})
			return
		}
		if (!code.value) {
			uni.showToast({
				icon: "none",
				title: "请输入验证码！"
			})
			return
		}
		if (!isAgree.value) {
			uni.showToast({
				icon: "none",
				title: "请同意隐私协议和用户协议！"
			})
			return
		}
		indexApi.login({
			phone: phone.value,
			code: code.value
		}).then(res => {
			uni.showToast({
				title: "登录成功"
			})
			if (res.data.ach == 1) {
				queryAnchorInfoByMemberId(res.data.id)
			}
			uni.setStorageSync('user', res.data)
			uni.setStorageSync('token', res.data.token)
			membergetLiveTokens()

		})
	}
	// 获取主播信息
	const queryAnchorInfoByMemberId = (id) => {
		userApi.queryAnchorInfoByMemberId({
			"member.id": id
		}).then(res => {
			uni.setStorageSync('anchor', res.data)
		})
	}
</script>

<style scoped>
	.bg-login {
		background: url(/static/login/bg_login.png) no-repeat;
		background-size: cover;
		width: 630rpx;
		height: 342rpx;
		box-sizing: border-box;
		padding: 20rpx 40rpx;
	}

	.my-20 {
		background-color: #E7F1F6 !important;
		border-radius: 0.3rem !important;
	}

	:deep(.uni-easyinput__content) {
		background-color: #E7F1F6 !important;
		border-radius: 0.3rem !important;
	}
</style>